package org.example.sprojcet.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.sprojcet.entitys.User;
import org.example.sprojcet.mapper.UserMapper;
import org.example.sprojcet.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    //登录接口
    @Override
    public SaResult login(User User) {
        System.out.println("登录请求参数: " + User.getPhone());
        
        //查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>();
        queryWrapper.eq(User::getPhone,User.getPhone());
        User user = userMapper.selectOne(queryWrapper);
        
        if(user==null) {
            System.out.println("用户不存在: " + User.getPhone());
            return SaResult.error("没有此用户");
        }
        
        System.out.println("查询到用户: " + user.getName() + ", 状态: " + user.getStatus());
        
        if(user.getStatus()!=0){
            System.out.println("账户状态异常: " + user.getStatus());
            return SaResult.error("账户处于异常状态");
        }else if(user.getPassword().equals(User.getPassword())) {
            //登录成功
            System.out.println("密码验证成功，开始登录...");
            StpUtil.login(User.getPhone());
            System.out.println("登录成功，Token: " + StpUtil.getTokenValue());
            return  SaResult.data(StpUtil.getTokenInfo());
        }else {
            System.out.println("密码错误");
            return SaResult.error("密码错误");
        }
    }

    @Override
    public SaResult logout(SaResult result) {
        StpUtil.logout();
        return SaResult.ok("退出成功");
    }

    @Override
    public SaResult saveUser(User user) {
        return null;
    }

//    /**
//     * 退出接口     发现一个问题，就是请求这个接口必须要携带token，如果没有携带token会导致redis中的数据还存在
//     * @return
//     */
//    @GetMapping("logout")
//    public SaResult logout() {
//        StpUtil.logout();
//        return SaResult.ok("退出成功");
//    }
}
